package com.rules.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rules.admin.dao.TreeNodeDao;
import com.rules.admin.entity.TreeNode;
import com.rules.admin.service.TreeDedutionService;
import com.rules.admin.service.TreeNodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TreeNodeServiceImpl extends ServiceImpl<TreeNodeDao, TreeNode> implements TreeNodeService {

   @Autowired
   private TreeDedutionService treeDedutionService;

   public List<TreeNode> getTreeNodesByTreeId(long treeId) {
      LambdaQueryWrapper<TreeNode> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(TreeNode::getTreeId, treeId);
      queryWrapper.orderByAsc(TreeNode::getCode);
      return this.baseMapper.selectList(queryWrapper);
   }

   public void deleteByTreeId(Long treeId) {
      LambdaQueryWrapper<TreeNode> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(TreeNode::getTreeId, treeId);
      this.baseMapper.delete(queryWrapper);
   }

   public void create(TreeNode treeNode) {
      treeNode.setCode(this.getTreeNodeCode(treeNode.getParentId()));
      this.save(treeNode);
   }

   public String getTreeNodeCode(Long parentId) {
      if (parentId == null) {
         return "001";
      } else {
         LambdaQueryWrapper<TreeNode> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.eq(TreeNode::getParentId, parentId);
         int count1 = this.baseMapper.selectCount(queryWrapper);
         int count2 = this.treeDedutionService.countByNodeId(parentId);

         String code = StringUtils.leftPad(Integer.toString(count1 + count2 + 1), 3, "0");
         TreeNode treeNode = (TreeNode)this.getById(parentId);
         return treeNode.getCode() + code;
      }
   }
}
